<!-- 待审批管理 -->
<template>
    <div class="leave-box">
        <!-- 查询 -->
        <el-form :inline="true" ref="leaveRuleFormRef" :model="leaveRuleForm" label-width="120px" class="demo-ruleForm"
            :size="formSize" status-icon>
            <el-form-item label="审批状态" prop="applyState">
                <el-select v-model="leaveRuleForm.applyState" placeholder="请选择审批状态">
                    <el-option :label="item.label" :value="item.value" v-for="item in options" :key="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="SubmitForm(leaveRuleFormRef)">查询</el-button>
                <el-button @click="resetForm(leaveRuleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 主体 -->
        <div class="table-but mb-5 mt-5">
            <el-button type="primary" @click="leaveApproval">审批休假</el-button>
        </div>
        <!-- 表格数据 -->
        <div class="table-box">
            <el-table :data="tableData" style="width: 100%">
                <!-- 表格标题 -->
                <el-table-column :label="item.label" :prop="item.property" v-for="(item, index) in columns" :key="index"
                    :formatter="item.formatter" :width="item.width" />
                <el-table-column align="center" label="操作" width="250px">
                    <template #default="scope">
                        <el-button size="small" @click="handleView(scope.row)">查看</el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.row)">作废</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="flex justify-center items-center mt-5">
                <el-pagination v-model:currentPage="pager.currentPage" v-model:page-size="pager.pageSize"
                    :page-sizes="[1, 3, 5, 10]" :small="small" :disabled="disabled" :background="background"
                    layout="total, sizes, prev, pager, next, jumper" :total="pager.total"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
            <!-- 对话框-审批休假 -->
            <el-dialog v-model="dialogVisible" title="审批休假" width="50%" draggable @close="dialogClose">
                <div>
                    <el-form ref="DialogRuleFormRef" :model="DialogRuleForm" :rules="rules" label-width="80px"
                        class="demo-ruleForm" :size="formSize" status-icon>
                        <el-form-item label="休假类型" prop="applyType">
                            <el-select v-model="DialogRuleForm.applyType" placeholder="选择休假类型">
                                <el-option :label="item.label" :value="item.value" v-for="item, index in DialogOptions"
                                    :key="index" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="休假时间" prop="allTime">
                            <el-date-picker v-model="DialogRuleForm.allTime" type="datetimerange"
                                start-placeholder="开始时间" end-placeholder="结束时间" :default-time="defaultTime1"
                                @change="handleChangeTime" />
                        </el-form-item>
                        <el-form-item label="休假时长" prop="remark">
                            <span>{{ daysDifference }}天</span>
                        </el-form-item>
                        <el-form-item label="休假原因" prop="reasons">
                            <el-input v-model="DialogRuleForm.reasons" placeholder="请输入休假原因" />
                        </el-form-item>
                    </el-form>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="DialogSubmitForm(DialogRuleFormRef)">确定</el-button>
                    </span>
                </template>
            </el-dialog>
            <!-- 对话框-查看 -->
            <el-dialog v-model="dialogVisible2" title="申请休假详情" width="45%" draggable>
                <div class="dialogClass">
                    <!-- 步骤条 -->
                    <el-steps :space="200" finish-status="success"
                        :active="userObj.applyState > 2 ? 3 : userObj.applyState" v-if="leaveRuleForm.applyState !== 5"
                        class="mb-5">
                        <el-step title="审批中" />
                        <el-step title="待审批" />
                        <el-step title="审批通过/拒绝" />
                    </el-steps>
                    <el-form class="demo-ruleForm" ref="leaveRuleFormRef2" :model="leaveRuleForm2" :size="formSize"
                        status-icon>
                        <el-form-item>
                            <span>休假类型：{{ userObj.applyType }}</span>
                        </el-form-item>
                        <el-form-item>
                            <span>休假时间：{{ userObj.time }}</span>
                        </el-form-item>
                        <el-form-item>
                            <span>休假时长：{{ userObj.leaveTime }}</span>
                        </el-form-item>
                        <el-form-item>
                            <span>休假原因：{{ userObj.reasons }}</span>
                        </el-form-item>
                        <el-form-item>
                            <span>审批状态：{{ userObj.applyStateName }}</span>
                        </el-form-item>
                        <el-form-item>
                            <span>申请人：{{ userObj.applyUser.userName }}</span>
                        </el-form-item>
                        <el-form-item>
                            <span>审核人：{{ userObj.curAuditUserName }}</span>
                        </el-form-item>
                    </el-form>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible2 = false">取消</el-button>
                        <el-button type="primary" @click="dialogVisible2 = false">确定</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
// import { validateMobile } from '../../utils/vaildate'
import api from '../../api'

//时间格式转换函数
const formatDate = (dateString: any) => {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');

    return `${year}-${month}-${day}`;
}
onMounted(() => {
    getleavelistapi(leaveRuleForm)
})
// 获取到审批列表的数据
const getleavelistapi = (obj?: any) => {
    api.getLeaveListApi({ ...obj, ...pager }).then((res: any) => {
        console.log(res);
        tableData.value = res.list
    })
}


// 头部查询
const formSize = ref('default')//用于控制该表单内组件的尺寸
const leaveRuleFormRef = ref<FormInstance>()//获取ref节点
//查询的数据
const leaveRuleForm = reactive({
    applyState: 0,
    type: 'approve'
})
//查询的数据格式
const options = [
    {
        value: 0,
        label: "全部",
    },
    {
        value: 1,
        label: "待审批",
    },
    {
        value: 2,
        label: "审批中",
    },
    {
        value: 3,
        label: "审批通过",
    },
    {
        value: 4,
        label: "审批拒绝",
    },
    {
        value: 5,
        label: "作废",
    },
];
//查询按钮
const SubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 调用全部审批列表接口
            getleavelistapi(leaveRuleForm)
        } else {
            console.log('error submit!', fields)
        }
    })
}
//重置按钮
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}



// 创建审批对话框
const dialogVisible = ref(false)//对话框开关
const action = ref('create')//判断对话框是创建还是作废
const DialogRuleFormRef = ref<FormInstance>()//获取ref节点
// 提交表单数据
const DialogRuleForm = reactive({
    applyType: '',//休假类型
    allTime: '',//休假时间
    reasons: ''//休假原因
})
//对话框里的休假类型
const DialogOptions = ref([
    {
        value: 1,
        label: "事假",
    },
    {
        value: 2,
        label: "病假",
    },
    {
        value: 3,
        label: "丧假",
    },
    {
        value: 4,
        label: "婚假",
    },
    {
        value: 5,
        label: "产假",
    },
    {
        value: 6,
        label: "陪产假",
    },
    {
        value: 7,
        label: "年假",
    },
    {
        value: 8,
        label: "调休",
    },
])
const defaultTime1 = [new Date()] // 选择时间后的默认值(时分秒)
//请假时长(几天)
const daysDifference = ref(0)
//选择时间改变回调
const handleChangeTime = (val: any) => {
    let date1: any = new Date(val[0]);//开始时间
    let date2: any = new Date(val[1]);//结束时间
    //计算时间差    请假的天数(Math.ceil向上取整)
    daysDifference.value = Math.ceil((date2 - date1) / (1000 * 60 * 60 * 24))
}
// 对话框 表单验证
const rules = reactive({
    applyType: [
        { required: true, message: "请输入休假类型", trigger: "blur" },
    ],
    allTime: [
        { required: true, message: "休假时间必填", trigger: "blur" },
    ],
})
//确定提交按钮
const DialogSubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            let params: any = DialogRuleForm//表单数据
            params.leaveTime = daysDifference.value//请假时长
            params.action = action.value//创建审批还是作废审批
            //调用创建审批接口
            api.getLeaveOperateApi(params).then(res => {
                if (res) {
                    ElMessage.success("申请成功")
                    //关闭对话框
                    dialogVisible.value = false
                    // 调用全部审批列表接口
                    getleavelistapi()
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
//对话框关闭回调
const dialogClose = () => {
    //重置表单数据
    resetForm(DialogRuleFormRef.value)
}
//审批休假按钮
const leaveApproval = () => {
    dialogVisible.value = true//开启对话框
}



// 主体表格
const tableData: any = ref()// 表单数据
// 表格标题
const columns = [
    {
        label: '单号',
        property: 'orderNo'
    },
    {
        label: '休假时间',
        property: 'allTime',
        width: '250px',
        formatter(_row: string, _column: string, cellValue: string) {
            let time1 = formatDate(cellValue[0])
            let time2 = formatDate(cellValue[1])
            return `${time1} 至 ${time2}`
        },
    },
    {
        label: '申请人',
        property: 'applyUser.userName',
    },
    {
        label: '审批状态',
        property: 'applyState',
        formatter(_row: string, _column: string, cellValue: string) {
            return {
                "1": "待审批",
                "2": "审批中",
                "3": "审批通过",
                "4": "审批拒绝",
                "5": "作废"
            }[cellValue]
        },
    },
    {
        label: '休假时长',
        property: 'leaveTime',
        formatter(_row: string, _column: string, cellValue: string) {
            return cellValue + '小时'
        },
    },
    {
        label: '休假类型',
        property: 'applyType',
        formatter(_row: string, _column: string, cellValue: string) {
            return {
                "1": "事假",
                "2": "病假",
                "3": "丧假",
                "4": "婚嫁",
                "5": "产假",
                "6": "陪产假",
                "7": "年假",
                "8": "调休",
            }[cellValue]
        },
    },
    {
        label: '休假原因',
        property: 'reasons',
        // width: '210px',
    },
    {
        label: '申请时间',
        property: 'createTime',
        formatter(_row: string, _column: string, cellValue: string) {
            let time1 = formatDate(cellValue)
            return `${time1}`
        },
    },

]
// 单个查看
const handleView = (row: User) => {
    dialogVisible2.value = true//开启对话框
    let data: any = { ...row }//将row对象深拷贝给data
    userObj.value = data
    data.applyType = data.applyType.toString()//number转为字符串
    const obj: any = {
        "1": "事假",
        "2": "病假",
        "3": "丧假",
        "4": "婚嫁",
        "5": "产假",
        "6": "陪产假",
        "7": "年假",
        "8": "调休"
    }
    const obj2: any = {
        "1": "待审批",
        "2": "审批中",
        "3": "审批通过",
        "4": "审批拒绝",
        "5": "作废"
    }
    userObj.value.applyType = obj[data.applyType]//类型转换
    userObj.value.applyStateName = obj2[data.applyState]//审批状态转换
    userObj.value.time = formatDate(data.allTime[0]) + ' 到 ' + formatDate(data.allTime[1])
}
// 作废
const handleDelete = (row: User) => {
    ElMessageBox.confirm(
        '您确定要作废吗?',
        '提示',
        {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
            draggable: true,//属性为true以做到拖拽
        }
    )
        .then(() => {
            // 调用删除数据接口
            api.getLeaveOperateApi({ _id: row._id }).then(res => {
                if (res) {
                    // 调用全部审批列表接口
                    getleavelistapi()
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除',
            })
        })
}

//对话框-查看
const dialogVisible2 = ref(false)
//点击的表单数据
const userObj = ref<LeaveApplication | any>({})
const leaveRuleFormRef2 = ref<FormInstance>()
const leaveRuleForm2 = reactive({

})



//分页
const pager = reactive({
    currentPage: 1,//初始化为第1页
    pageSize: 10,//一页多少条数据
    total: 0,//总条数
})
const small = ref(false)//是否使用小型分页样式
const background = ref(false)//是否为分页按钮添加背景色
const disabled = ref(false)//是否禁用分页
//一页的条数改变时触发
const handleSizeChange = (val: number) => {
    pager.pageSize = val
    // 调用全部审批列表接口
    getleavelistapi()
}
//当前页变动时候触发
const handleCurrentChange = (val: number) => {
    pager.currentPage = val
    // 调用全部审批列表接口
    getleavelistapi()
}
</script>

<style scoped lang="less">
.el-select {
    width: 200px;
}

.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}

.dialogClass {
    // padding: 0px auto;
    margin-left: 100px
}
</style>